// 获取画布和上下文
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');

// 画布尺寸
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 400;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;

// 球的半径
const BALL_RADIUS = 15;

// 球数组
let balls = [];

// 初始化球
function initBalls() {
    // 白球
    balls.push({
        x: CANVAS_WIDTH / 4,
        y: CANVAS_HEIGHT / 2,
        dx: 0,
        dy: 0,
        color: 'white'
    });

    // 彩球示例
    balls.push({
        x: 3 * CANVAS_WIDTH / 4,
        y: CANVAS_HEIGHT / 2,
        dx: 0,
        dy: 0,
        color: 'red'
    });
}

// 绘制球
function drawBalls() {
    balls.forEach(ball => {
        ctx.beginPath();
        ctx.arc(ball.x, ball.y, BALL_RADIUS, 0, Math.PI * 2);
        ctx.fillStyle = ball.color;
        ctx.fill();
        ctx.closePath();
    });
}

// 移动球
function moveBalls() {
    balls.forEach(ball => {
        ball.x += ball.dx;
        ball.y += ball.dy;

        // 边界检测
        if (ball.x - BALL_RADIUS < 0 || ball.x + BALL_RADIUS > CANVAS_WIDTH) {
            ball.dx = -ball.dx;
        }
        if (ball.y - BALL_RADIUS < 0 || ball.y + BALL_RADIUS > CANVAS_HEIGHT) {
            ball.dy = -ball.dy;
        }
    });

    // 球之间的碰撞检测
    for (let i = 0; i < balls.length; i++) {
        for (let j = i + 1; j < balls.length; j++) {
            const ball1 = balls[i];
            const ball2 = balls[j];
            const dx = ball2.x - ball1.x;
            const dy = ball2.y - ball1.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            if (distance < 2 * BALL_RADIUS) {
                // 简单的碰撞处理
                const tempDx = ball1.dx;
                const tempDy = ball1.dy;
                ball1.dx = ball2.dx;
                ball1.dy = ball2.dy;
                ball2.dx = tempDx;
                ball2.dy = tempDy;
            }
        }
    }
}

// 处理鼠标点击，给白球施加力
canvas.addEventListener('click', function (event) {
    const rect = canvas.getBoundingClientRect();
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;
    const whiteBall = balls[0];
    const dx = mouseX - whiteBall.x;
    const dy = mouseY - whiteBall.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    const force = 0.1;
    whiteBall.dx = dx / distance * force;
    whiteBall.dy = dy / distance * force;
});

// 主游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    drawBalls();
    moveBalls();

    requestAnimationFrame(gameLoop);
}

// 初始化游戏
initBalls();
gameLoop();